# _*_ coding:utf-8 _*_
# @Time : 2023/5/25 17:57
# @Author : wsl
# @File : day05_demo
# @Project : python  xpath解析 安装lxmp库 E:\python\Scripts
import urllib.request
import urllib.error
from lxml import etree


# https://sc.chinaz.com/tupian/fengjing.html
# https://sc.chinaz.com/tupian/fengjing_2.html
# https://sc.chinaz.com/tupian/fengjing_3.html


def create_request(page1):
    if page1 == 1:
        url = 'https://sc.chinaz.com/tupian/fengjing.html'
    else:
        url = 'https://sc.chinaz.com/tupian/fengjing_' + str(page1) + '.html'

    print(url)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/113.0'
    }

    request1 = urllib.request.Request(url=url, headers=headers)
    return request1


def get_content(request1):
    response = urllib.request.urlopen(request1)
    content1 = response.read().decode('utf‐8')
    return content1


def down_load(content1):
    # 图片地址 文件名字
    tree = etree.HTML(content1)
    path_list = tree.xpath('//div[@class="container"]//img/@data-original')
    name_list = tree.xpath('//div[@class="container"]//img/@alt')

    for i in range(len(name_list)):
        name = name_list[i]
        path = 'https:' + path_list[i]
        print(name, path)

        urllib.request.urlretrieve(url=path, filename='../image/output/tupian/' + name + '.jpg')


if __name__ == '__main__':
    start_page = int(input('起始页码'))  # string ->int
    end_page = int(input('结束页码'))

    for page in range(start_page, end_page + 1):
        request = create_request(page)
        content = get_content(request)
        down_load(content)
